#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define HELLO_PORT 12345
#define HELLO_GROUP "239.42.5.1"
#define ASK_IP "1|X.X.X.X|"
#define ASK_SYN "2|X.X.X.X|"
#define GIVE_file "3|X.X.X.X|"
#define MD5 "5|X.X.X.X|"

char* get_md5(char *filename)
{

  FILE *fd;
  FILE *f;
  char *tmp;

  tmp = malloc (60 * sizeof(char));
  tmp = strcpy(tmp, "md5sum ");
  tmp = strcat (tmp, filename);
  tmp = strcat (tmp, " > md5.tmp");
  f = fopen(filename, "r");
  if (f == NULL)
    return NULL;
  else
    fclose(f);
  system(tmp);

  fd = fopen("md5.tmp","r");

  if (fd != NULL)
    {
      fscanf (fd, "%s", tmp);
    }

  fclose(fd);
  return tmp;
}

main(int argc, char *argv[])
{
     struct sockaddr_in addr;
     int fd, cnt;
     struct ip_mreq mreq;
     char *message = NULL;

     if (argc <= 1)
     {
       printf("Usage :you can choose 1 to ask @IP of all SAN servers\n2 to ask synchronisation\n3 to send your file list\nthe cmd 3 you should give the list in argv[2] by the format 'file_name|file_name'\n5 to ask check md5; with the argv[2] is the 'file_name'\n");
       exit(1);
     }
     else
     {
       if (strcmp(argv[1], "1") == 0)
	 message = ASK_IP;
       if (strcmp(argv[1], "2") == 0)
	 message = ASK_SYN;
       if (strcmp(argv[1], "3") == 0 && argv[2] != NULL)
       {
	 message = malloc(strlen(message) + strlen(argv[2]));
	 message = GIVE_file;
	 message = strcat(message,argv[2]);
       }
       else
       {
	 if (strcmp(argv[1], "3") == 0 && argc <= 2)
	 {
	   printf("yous should give files!\n");
	   exit(2);
	 }
       }
       if (strcmp(argv[1], "5") == 0 && argv[2] != NULL)
       {
	 char *tmp = get_md5(argv[2]);
	 if (tmp == NULL)
	 {
	   printf("the file is not there\n");
	   exit(2);
	 }
	 int i = strlen(argv[2]) + strlen(tmp) + strlen(MD5) + 2;
	 message = malloc((i) * sizeof (char));
	 message = strcpy(message, MD5);
	 message = strcat(message, argv[2]);
	 message = strcat(message, "|");
	 message = strcat(message, tmp);
	 message = strcat(message, "|");
       }
       else
       {
	 if (strcmp(argv[1], "5") == 0 && argc <= 2)
	 {
	   printf("yous should give file name!\n");
	   exit(2);
	 }
       }
       printf("the cmd is %s\n",message);
       /* create what looks like an ordinary UDP socket */
       if ((fd=socket(AF_INET,SOCK_DGRAM,0)) < 0) {
	 perror("socket");
	 exit(1);
       }

       /* set up destination address */
       memset(&addr,0,sizeof(addr));
       addr.sin_family=AF_INET;
       addr.sin_addr.s_addr=inet_addr(HELLO_GROUP);
       addr.sin_port=htons(HELLO_PORT);

       /* now just sendto() our destination! */
       if (sendto(fd,message, strlen(message),0,(struct sockaddr *) &addr,
		  sizeof(addr)) < 0)
       {
	 perror("sendto");
	 exit(1);
       }
       sleep(1);
     }
}
